﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Mvc.StarterSite.Controllers;
using MvcEngine.Mvc.Models.ViewModels;
using System.Web.Mvc;
using MvcEngine.Blog.Models.Entities;
using MvcEngine.Core;
using MvcEngine.Core.Common.Slugs;
using BlogML.Xml;
using MvcEngine.Core.Repositories;
using MvcEngine.Blog.Repositories;
using MvcEngine.Blog.Components.Extensions;
using System.Web;
using MvcEngine.Blog.Models.ViewData;
using MvcEngine.Blog.Helper;
using MvcEngine.Core.Helpers;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Blog.Filters;
using MvcEngine.Mvc;
using MvcEngine.Mvc.Filters;
using MvcEngine.Blog.Managers;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Blog.Models;

namespace MvcEngine.Blog.BackOffice.Controllers
{
    public class BlogCommonController : BaseController
    {

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel List()
        {
            var blogs = BlogManager.Current.GetBlogs();
            return new MvcEngineModelItem<IList<BlogData>>() { Item = blogs, ViewName = "List" };
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel BlogHeader()
        {
            return new MvcEngineModelItem<BlogData>()
            {
                Item = BlogManager.Current.GetCurrentBlog(),
                ViewName = "BlogHeader"
            };
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel BlogSettings(Guid blogId)
        {
            var blog = BlogManager.Current.GetBlog(blogId);

            return new BlogDataSettingsViewModel()
            {
                AllowComments = blog.AllowComments,
                ShowCaptcha = blog.ShowCaptcha,
                BlogId = blog.Id,
                DaysCommentsAreEnabled = blog.DaysCommentsAreEnabled,
                PostsInRss = blog.PostsInRss,
                BlogDescription = blog.BlogDescription,
                Email = blog.Email,
                EmailSubjectPrefix = blog.EmailSubjectPrefix,
                HtmlHeader = blog.HtmlHeader,
                BlogName = blog.BlogName,
                Name = blog.Name,
                PostsPerPage = blog.PostsPerPage,
                SendMailOnComment = blog.SendMailOnComment,
                SmtpPassword = blog.SmtpPassword,
                SmtpServer = blog.SmtpServer,
                SmtpServerPort = blog.SmtpServerPort,
                SmtpUserName = blog.SmtpUserName
            };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AntiForgeryValidationFilter]
        [ValidateInput(false)]
        public object BlogSettingsSave(string blogName, BlogData data)
        {
            if (ModelState.IsValid)
            {
                var blog = BlogManager.Current.GetBlog(blogName);
                data.PageId = blog.PageId;
                BlogManager.Current.Save(data);
                return Json(new { model = "valid" });
            }
            return Json(new { model = "invalid", errors = ModelState.GetErrors() });
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel BlogInstall()
        {
            return new MvcEngineModel();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("BlogInstall")]
        public object BlogInstallSave(string name, Guid pageId)
        {
            BlogData blog = new BlogData() { Name = name, PageId = pageId, Id = Guid.NewGuid() };
            BlogManager.Current.Save(blog);

            return Text(string.Empty);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel BlogImport()
        {
            return new MvcEngineModel();
        }

        //[AcceptVerbs(HttpVerbs.Post)]
        //[AntiForgeryValidationFilter]
        //public ActionResult BlogImport(Guid blogId, HttpPostedFileBase file)
        //{
        //    BlogMLBlog blog = BlogMLSerializer.Deserialize(file.InputStream);

        //    List<BlogTagBase> tags = tagRepository.GetAll(blogId).ToList();

        //    using (IUnitOfWork unitOfWorkHelper = UnitOfWorkHelper.Get())
        //    {
        //        foreach (var item in blog.Categories)
        //        {
        //            BlogCategory category = IoC.Resolve<BlogCategory>();
        //            category.Name = item.Title;
        //            if (item.DateCreated == DateTime.MinValue)
        //                category.CreatedDate = DateTime.Now;
        //            else
        //                category.CreatedDate = item.DateCreated;
        //            if (item.DateModified == DateTime.MinValue)
        //                category.ModifiedDate = DateTime.Now;
        //            else
        //                category.ModifiedDate = item.DateModified;
        //            category.Id = new Guid(item.ID);
        //            category.BlogId = blogId;
        //            category.Slug = IoC.Resolve<ISlugConverter>().Convert(item.Title);
        //            categoryRepository.Add(category);
        //        }

        //        foreach (var item in blog.Posts)
        //        {
        //            BlogPost post = IoC.Resolve<BlogPost>();
        //            post.Comments = new List<BlogPostComment>();
        //            post.Tags = new List<BlogTagBase>();
        //            post.Categories = new List<BlogCategory>();

        //            post.Title = item.Title;
        //            post.Author = item.Authors[0].Ref;
        //            post.Description = item.Excerpt.Text;
        //            post.IsCommentEnabled = true;
        //            post.PostContent = item.Content.Text;
        //            if (item.DateCreated == DateTime.MinValue)
        //                post.CreatedDate = DateTime.Now;
        //            else
        //                post.CreatedDate = item.DateCreated;
        //            if (item.DateModified == DateTime.MinValue)
        //                post.ModifiedDate = DateTime.Now;
        //            else
        //                post.ModifiedDate = item.DateModified;

        //            if (item.Approved == true)
        //                post.PublishedDate = item.DateCreated;
        //            else
        //                post.PublishedDate = null;
        //            post.Id = new Guid(item.ID);
        //            post.BlogId = blogId;

        //            string slug = item.PostUrl.Split('/').Last().Replace(".aspx", string.Empty);
        //            post.Slug = slug;

        //            foreach (BlogMLCategoryReference category in item.Categories)
        //            {
        //                BlogCategory newCategory = IoC.Resolve<BlogCategory>();
        //                newCategory.Id = new Guid(category.Ref);
        //                post.Categories.Add(newCategory);
        //            }

        //            foreach (BlogML.Xml.BlogMLTag tag in item.Tags)
        //            {
        //                BlogTagBase newTag = tags.SingleOrDefault(t => t.Name == tag.Ref && t.BlogId == blogId);
        //                if (newTag == null)
        //                {
        //                    newTag = IoC.Resolve<BlogTagBase>();
        //                    newTag.Id = Guid.NewGuid();
        //                    newTag.Name = tag.Ref;
        //                    newTag.Slug = IoC.Resolve<ISlugConverter>().Convert(tag.Ref);
        //                    if (tag.DateCreated == DateTime.MinValue)
        //                        newTag.CreatedDate = DateTime.Now;
        //                    else
        //                        newTag.CreatedDate = tag.DateCreated;
        //                    if (tag.DateModified == DateTime.MinValue)
        //                        newTag.ModifiedDate = DateTime.Now;
        //                    else
        //                        newTag.ModifiedDate = tag.DateModified;
        //                    newTag.BlogId = blogId;

        //                    tagRepository.Add(newTag);
        //                    tags.Add(newTag);
        //                }
        //                post.Tags.Add(newTag);
        //            }

        //            postRepository.Update(post);

        //            foreach (BlogML.Xml.BlogMLComment cmt in item.Comments)
        //            {
        //                BlogPostComment comment = IoC.Resolve<BlogPostComment>();
        //                comment.Author = cmt.UserName;
        //                comment.Comment = cmt.Content.Text;
        //                comment.IsApproved = cmt.Approved;
        //                if (cmt.DateCreated == DateTime.MinValue)
        //                    comment.CreatedDate = DateTime.Now;
        //                else
        //                    comment.CreatedDate = cmt.DateCreated;
        //                if (cmt.DateModified == DateTime.MinValue)
        //                    comment.ModifiedDate = DateTime.Now;
        //                else
        //                    comment.ModifiedDate = cmt.DateModified;
        //                comment.Id = new Guid(cmt.ID);
        //                comment.PostId = post.Id;
        //                comment.Ip = "";
        //                comment.Email = cmt.UserEMail;
        //                comment.Website = cmt.UserUrl;
        //                commentRepository.Add(comment);
        //            }
        //        }
        //        unitOfWorkHelper.Commit();
        //    }
        //    return Redirect(Url.BlogImport());
        //}

    }
}
